package cn.hty.mymsg.api.action.recall;

import cn.hty.mymsg.api.domain.RecallTaskModel;
import cn.hty.mymsg.common.constant.CommonConstant;
import cn.hty.mymsg.common.domain.RecallTaskInfo;
import cn.hty.mymsg.common.enums.RespStatusEnum;
import cn.hty.mymsg.common.pipeline.BusinessProcess;
import cn.hty.mymsg.common.pipeline.ProcessContext;
import cn.hty.mymsg.common.vo.BasicResultVO;
import cn.hty.mymsg.dao.MessageTemplateDao;
import cn.hty.mymsg.domain.MessageTemplate;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 组装撤回参数
 */
@Slf4j
@Service
public class RecallAssembleAction implements BusinessProcess<RecallTaskModel> {
    @Autowired
    private MessageTemplateDao messageTemplateDao;
    @Override
    public void process(ProcessContext<RecallTaskModel> context) {
        //获得撤回任务模型和模板id
        RecallTaskModel recallTaskModel = context.getProcessModel();
        Long messageTemplateId = recallTaskModel.getMessageTemplateId();
        try {

            Optional<MessageTemplate> messageTemplate = messageTemplateDao.findById(messageTemplateId);
            //判断是否为空，空就设置中断
            if (!messageTemplate.isPresent() || messageTemplate.get().getIsDeleted().equals(CommonConstant.TRUE)){
                context.setNeedBreak(true).setResponse(BasicResultVO.fail(RespStatusEnum.TEMPLATE_NOT_FOUND));
                return;
            }
            //组装撤回任务信息
            RecallTaskInfo recallTaskInfo = RecallTaskInfo.builder().messageTemplateId(messageTemplateId)
                    .recallMessageId(recallTaskModel.getRecallMessageId())
                    .sendAccount(messageTemplate.get().getSendAccount())
                    .sendChannel(messageTemplate.get().getSendChannel())
                    .build();
            recallTaskModel.setRecallTaskInfo(recallTaskInfo);
        } catch (Exception e) {
            context.setNeedBreak(true).setResponse(BasicResultVO.fail(RespStatusEnum.SERVICE_ERROR));
            log.error("assemble recall task fail! templateId:{}, e:{}", messageTemplateId, Throwables.getStackTraceAsString(e));
        }
    }
}
